package com.icode.service.impl.user;

import com.icode.core.dto.user.MemberDTO;
import com.icode.core.model.user.Member;
import com.icode.dao.MemberDao;
import com.icode.service.user.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-3-16
 * Time: 上午10:53
 * To change this template use File | Settings | File Templates.
 */
@Service("memberService")
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;


    @Override
    public List<MemberDTO> findAllMember() {
        List<Member> members = memberDao.findAll(Member.class);
        List<MemberDTO> memberDTOs = MemberDTO.toDTOs(members);
        return memberDTOs;
    }

    @Override
    @Transactional
    public MemberDTO findMemberByGuid(String guid) {
        Member member;
        try {
            member = memberDao.findByGuid(Member.class, guid);
        } catch (Exception e) {
            return null;
        }
        MemberDTO memberDTO = MemberDTO.toDTO(member);
        return memberDTO;
    }

    @Override
    @Transactional
    public void saveOrUpdateMember(MemberDTO memberDTO) {
        if ("".equals(memberDTO.getId())) {
            Member member = MemberDTO.toMember(memberDTO);
            memberDao.saveOrUpdate(member);
        } else {
            Member member = memberDao.findByGuid(Member.class, memberDTO.getGuid());
            member.initMember(memberDTO);
            memberDao.saveOrUpdate(member);
        }
    }

    @Override
    @Transactional
    public void deleteMemberByGuid(String guid) {
        memberDao.delete(guid, Member.class);
    }

    @Override
    @Transactional
    public List<MemberDTO> findMemberByMore(String name, String idCard, String phoneNum) {
        String sql = "";
        if (!"".equals(name)) {
            sql += " and a.name like " + "'%" + name + "%'";
        }
        if (!"".equals(idCard)) {
            sql += " and a.idCard like " + "'%" + idCard + "%'";
        }
        if (!"".equals(phoneNum)) {
            sql += " and a.phoneNum like " + "'%" + phoneNum + "%'";
        }
        List<Member> members = memberDao.findMemberByMore(sql);
        List<MemberDTO> memberDTOs = MemberDTO.toDTOs(members);
        return memberDTOs;
    }
}
